//
//  AddChaseViewController.m
//  PlayerWorld
//
//  Created by 汪的一声就哭了！ on 16/8/19.
//  Copyright © 2016年 刘成. All rights reserved.
//

#import "AddChaseViewController.h"
#import "AddChaseHeader.h"
#import "LZFoldButton.h"
#import "AddChase1TableViewCell.h"
#import "AddChase2TableViewCell.h"
#import "AddChase3TableViewCell.h"
#import "AFNetworking.h"
#import "AddChaseModel.h"
#import "ConfirmationBetViewController.h"
@interface AddChaseViewController ()<UITableViewDelegate, UITableViewDataSource, LZFoldButtonDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) AddChaseHeader *header;
@property (nonatomic, strong) LZFoldButton *lzBtn;
@property (nonatomic, assign) NSInteger type;
@end

@implementation AddChaseViewController
{
    NSMutableArray *_listArr;
    NSMutableArray *_boolArr;
    //倍数
    NSInteger _multiply;
    //最低收益率
    CGFloat _return;
    //追号期数
    NSInteger _issueNum;
    //相隔**期
    NSInteger _separateIssue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self obtainData];
    self.title = @"我要追号";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64-50) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[AddChase2TableViewCell class] forCellReuseIdentifier:@"cell1"];
    [self.tableView registerClass:[AddChase1TableViewCell class] forCellReuseIdentifier:@"cell2"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AddChase3TableViewCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    [self.view addSubview:self.lzBtn];
    self.header = [[AddChaseHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 40)];
    self.tableView.tableHeaderView = _header;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_header addGestureRecognizer:tap];
    self.type = 1;
    UIButton *getChaseOrder = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:getChaseOrder];
    getChaseOrder.frame = CGRectMake(0, self.view.bounds.size.height-64-50, self.view.bounds.size.width*2/3, 50);
    getChaseOrder.backgroundColor = [UIColor colorWithRed:36/255.0f green:11/255.0f blue:54/255.0f alpha:1];
    [getChaseOrder setTitle:@"生成追号单" forState:UIControlStateNormal];
    [getChaseOrder setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [getChaseOrder addTarget:self action:@selector(getChaseOrderAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:sureBtn];
    sureBtn.frame = CGRectMake(self.view.bounds.size.width*2/3, self.view.bounds.size.height-64-50, self.view.bounds.size.width/3, 50);
    sureBtn.backgroundColor = [UIColor colorWithRed:94/255.0f green:31/255.0f blue:139/255.0f alpha:1];
    [sureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)addaLZBtnWithInt:(NSInteger)integer
{
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < 69; i++) {
        NSString *str = [NSString stringWithFormat:@"%ld期  ",i];
        [array addObject:str];
    }
    self.lzBtn = [[LZFoldButton alloc] initWithFrame:CGRectMake(130, 60, 90, 43) dataArray:array];
    [self.tableView addSubview:self.lzBtn];
    self.lzBtn.lzDelegate = self;
    self.lzBtn.lzFontSize = 12;
    self.lzBtn.lzHeight = 400;
    self.lzBtn.lzButtonType = 1;
    
    [self.lzBtn LZSetTitle:@"2期  " forState:UIControlStateNormal];
    [self.lzBtn LZSetImage:[UIImage imageNamed:@"icon_select_arrow"] forState:UIControlStateNormal];
    [self.lzBtn LZSetImage:[UIImage imageNamed:@"icon_select_arrow"] forState:UIControlStateSelected];
    [self.lzBtn LZSetTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.lzBtn setLzTitleFontSize:16];
}
- (void)LZFoldButton:(LZFoldButton*)foldButton didSelectObject:(id)obj
{
    NSString *numStr = [obj substringToIndex:[obj length]-3];
//    NSLog(@"%@",numStr);
    _issueNum = [numStr integerValue];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section < 2) {
        if (self.type == 2 && section == 1) {
            return 2;
        }
        return 3;
    }
    return _listArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = 0;
    for (NSNumber *number in _boolArr) {
        if ([number boolValue]) {
            index++;
        }
    }
    if (indexPath.section == 0) {
        AddChase2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            if (indexPath.row == 0) {
                cell.mainLabel.text = @"追号期数";
                cell.detailLabel.text = @"";
            }
            else if (indexPath.row == 1){
                cell.mainLabel.text = @"总期数";
                cell.detailLabel.text = [NSString stringWithFormat:@"%ld期",index];
            }
            else if (indexPath.row == 2){
                cell.mainLabel.text = @"追号总金额";
                if (self.type == 3) {
                    NSInteger one_money = 0;
                    for (NSInteger i = 0; i < _issueNum ; i++) {
                        one_money = one_money+[self multiplicationInt:_multiply andFlag:i/_separateIssue];
                    }
                    cell.detailLabel.text = [NSString stringWithFormat:@"%ld元",one_money];
                }
                else{
                    cell.detailLabel.text = [NSString stringWithFormat:@"%ld元",index*_multiply];
                }
            }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 1){
        AddChase1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.textField.delegate = self;
        cell.textField.tag = indexPath.row + 1000*self.type;
        if (self.type == 1) {
            if (indexPath.row == 0) {
                cell.label.text = @"起始倍数";
                cell.textField.text = [NSString stringWithFormat:@"%ld",_multiply];
                cell.backLabel.text = @"";
            }
            else if (indexPath.row == 1){
                cell.label.text = @"最低收益率";
                cell.textField.text = [NSString stringWithFormat:@"%.0f",_return];
                cell.backLabel.text = @"%";
            }
            else if (indexPath.row == 2){
                cell.label.text = @"追号期数";
                cell.textField.text = [NSString stringWithFormat:@"%ld",index];
                cell.backLabel.text = @"期";
            }
        }else if (self.type == 2){
            if (indexPath.row == 0) {
                cell.label.text = @"起始倍数";
                cell.textField.text = [NSString stringWithFormat:@"%ld",_multiply];
                cell.backLabel.text = @"";
            }
            else if (indexPath.row == 1){
                cell.label.text = @"追号期数";
                cell.textField.text = [NSString stringWithFormat:@"%ld",index];
                cell.backLabel.text = @"期";
            }
        }else if (self.type == 3){
            if (indexPath.row == 0) {
                cell.label.text = @"隔";
                cell.textField.text = [NSString stringWithFormat:@"%ld",_separateIssue];
                cell.backLabel.text = @"期";
            }
            else if (indexPath.row == 1){
                cell.label.text = @"倍*";
                cell.textField.text = [NSString stringWithFormat:@"%ld",_multiply];
                cell.backLabel.text = @"";
            }
            else if (indexPath.row == 2){
                cell.label.text = @"追号期数";
                cell.textField.text = [NSString stringWithFormat:@"%ld",index];
                cell.backLabel.text = @"期";
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section == 2){
        AddChase3TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        AddChaseModel *model = [_listArr objectAtIndex:indexPath.row];
        cell.issueLabel.text = [NSString stringWithFormat:@"期号：%@",model.G_T_Issue];
        cell.endTimeLabel.text = [NSString stringWithFormat:@"截止：%@",model.G_T_EndTime];
        cell.mutipleLabel.text = [NSString stringWithFormat:@"%ld",_multiply];
        NSMutableAttributedString *attStr;
        if (self.type != 3) {
            attStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"金额：%.2f",(CGFloat)_multiply] attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
        }
        else{
            attStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"金额：%.2f",(CGFloat)[self multiplicationInt:_multiply andFlag:indexPath.row/_separateIssue]] attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
        }
        [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 3)];
        cell.moneyLabel.attributedText = attStr;
        if ([_boolArr[indexPath.row] boolValue]) {
            cell.headImageView.image = [UIImage imageNamed:@"追号2"];
        }
        else{
            cell.headImageView.image = [UIImage imageNamed:@"追号3"];
        }
        return cell;
    }
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        return 82;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
#pragma mark -- 头视图点击方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    //设置默认值
    _multiply = 1;
    _return = 50.0;
    _issueNum = 2;
    CGPoint point = [tap locationInView:self.header];
    if (point.x < self.view.bounds.size.width/3) {
        self.type = 1;
        [UIView animateWithDuration:0.3 animations:^{
            self.header.label1.textColor = [UIColor whiteColor];
            self.header.label2.textColor = [UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.label3.textColor = [UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.imageView.center = CGPointMake(self.view.bounds.size.width/6, self.header.center.y);
        }];
    }else if (point.x < self.view.bounds.size.width * 2 / 3){
        self.type = 2;
        [UIView animateWithDuration:0.3 animations:^{
            self.header.label1.textColor = [UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.label2.textColor = [UIColor whiteColor];
            self.header.label3.textColor = [UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.imageView.center = CGPointMake(self.view.bounds.size.width/2, self.header.center.y);
        }];
    }
    else{
        self.type = 3;
        [UIView animateWithDuration:0.3 animations:^{
            self.header.label1.textColor = [UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.label2.textColor =[UIColor colorWithRed:57.0/255.0 green:57.0/255.0 blue:57.0/255.0 alpha:1];
            self.header.label3.textColor = [UIColor whiteColor];
            self.header.imageView.center = CGPointMake(self.view.bounds.size.width*5/6, self.header.center.y);
            //设置默认值
            _multiply = 2;
            _separateIssue = 1;
        }];
    }
    
    [self.tableView reloadData];
}
#pragma mark --textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (![self isPureInt:textField.text] || ![self isPureFloat:textField.text]) {
        textField.text = @"";
    }
    if (textField.tag == 1000) {
        _multiply = [textField.text integerValue];
    }
    if (textField.tag == 1001) {
        _return = [textField.text floatValue];
    }
    if (textField.tag == 2000) {
        _multiply = [textField.text integerValue];
    }
    if (textField.tag == 2001) {
        _issueNum = [textField.text integerValue];
    }
    if (textField.tag == 3000) {
        _separateIssue = [textField.text integerValue];
    }
    if (textField.tag == 3001) {
        _multiply = [textField.text integerValue];
    }
    if (textField.tag == 3002) {
        _issueNum = [textField.text integerValue];
    }
}
#pragma mark --   判断是否为浮点形
- (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
#pragma mark - 判断字符串是不是数字
- (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}
#pragma mark --乘方
- (NSInteger)multiplicationInt:(NSInteger)buttom andFlag:(NSInteger)flag
{
    NSInteger integer = 1;
    for (NSInteger i = 0; i < flag; i++) {
        integer = integer*buttom;
    }
    return integer;
}
#pragma mark --数据处理
-(void)obtainData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Game" forKey:@"Model"];
    [parametersDic setObject:@"GetChaseCodeList" forKey:@"Action"];
    [parametersDic setObject:self.G_N_Id forKey:@"Id"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
        _listArr = [NSMutableArray array];
        _boolArr = [NSMutableArray array];
        for (NSDictionary *dict in [dic objectForKey:@"list"]) {
            AddChaseModel *model = [[AddChaseModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [_listArr addObject:model];
            [_boolArr addObject:[NSNumber numberWithBool:NO]];
        }
        //设置默认值
        _multiply = 1;
        _return = 50.0;
        _issueNum = 2;
        
        [self.tableView reloadData];
        [self addaLZBtnWithInt:_listArr.count];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}
-(void)obtainData1
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Game" forKey:@"Model"];
    [parametersDic setObject:@"AddBuy" forKey:@"Action"];
    [parametersDic setObject:self.G_N_Id forKey:@"Id"];
    [parametersDic setObject:self.Issue forKey:@"Issue"];
    [parametersDic setObject:[NSString stringWithFormat:@"%@+%@+%@",_G_P_Id,_codeString,_money] forKey:@"BuyCode"];
    NSInteger one_money = 0;
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < _issueNum; i++) {
        AddChaseModel *model = [_listArr objectAtIndex:i];
        NSString *string;
        if (self.type != 3) {
            string = [NSString stringWithFormat:@"%@+%ld",model.G_T_Issue,_multiply];
            one_money = one_money+_multiply;
        }
        else{
            string = [NSString stringWithFormat:@"%@+%ld",model.G_T_Issue,[self multiplicationInt:_multiply andFlag:i/_separateIssue]];
            one_money = one_money+[self multiplicationInt:_multiply andFlag:i/_separateIssue];
        }
        [array addObject:string];
    }
    NSString *bigStr = [array componentsJoinedByString:@"#"];
    [parametersDic setObject:bigStr forKey:@"BuyChase"];
    [parametersDic setObject:@"0" forKey:@"IsChaseCode"];
    [parametersDic setObject:[NSString stringWithFormat:@"%ld",_multiply] forKey:@"Multiple"];
    [parametersDic setObject:self.Rebate forKey:@"Rebate"];
    [parametersDic setObject:[NSString stringWithFormat:@"%.4f",(CGFloat)(one_money*[self.Multiple integerValue]*[self.money integerValue])] forKey:@"TheTotalAmount"];
    NSLog(@"%@",parametersDic);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[dic objectForKey:@"msg"] isEqualToString:@"投注成功"]) {
        ConfirmationBetViewController *cbVC= [[ConfirmationBetViewController alloc] init];
            cbVC.money = [NSString stringWithFormat:@"%.4f",(CGFloat)(one_money*[self.Multiple integerValue]*[self.money integerValue])];
            [self.navigationController pushViewController:cbVC animated:YES];
        }
        else{
            UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"提示信息" message:[dic objectForKey:@"msg"] preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alerView addAction:action];
            [self presentViewController:alerView animated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}

#pragma mark --生成追号单
- (void)getChaseOrderAction:(UIButton *)btn
{
    if (_issueNum < 2) {
        UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"提示信息" message:@"追号至少选择两位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alerView addAction:action];
        [self presentViewController:alerView animated:YES completion:nil];
    }
    else{
    for (NSInteger i = 0; i < _issueNum; i++) {
        [_boolArr setObject:[NSNumber numberWithBool:YES] atIndexedSubscript:i];
    }
    [self.tableView reloadData];
    }
}
#pragma mark -- 确认
- (void)sureBtnAction:(UIButton *)button
{
    [self obtainData1];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
